package com.wiz.weixin.manager;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.tencent.vo.WxMenu;
import com.wiz.weixin.util.TencentUtil;

import net.sf.json.JSONObject;

/**
 * 微信菜单管理
 * @author Hakeny
 */
@Service("menuManager")
public class MenuManager implements TencentConstant{
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private HttpManager httpManager;
	@Resource
	private WxMenuXmlParseFactory menuXmlFactory;
	@Resource
	private Gson gson;
	
	// 菜单创建（POST） 限次/天）
	 private final String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create";

	/**
	 * 创建菜单
	 *
	 * @param menu 菜单实例
	 * @return 表示成功，其他值表示失败
	 * @throws JSONException 
	 */
	private int createMenu(WxMenu menu) throws JSONException {
		int result = 0;
		// 将菜单对象转换成json 字符串
//		String jsonMenu = gson.toJson(menu, new TypeToken<WxMenu>(){}.getType());
		String jsonMenu = JSONObject.fromObject(menu).toString();
		// 拼装参数
		String requestUrl = menu_create_url + "?access_token=" + WxAccessManager.getTencent_wx_token();
		// 调用接口创建菜单
		String response = TencentUtil.httpsRequest(requestUrl, "POST", jsonMenu);
		if(StringUtils.isBlank(response)){
			return 1;
		}
		org.json.JSONObject jsonObject = new org.json.JSONObject(response);
		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				log.error("创建菜单失败errcode:{} errmsg:{}",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"));
			}
		}
		return result;
	}
	
	public int getMenu() throws JSONException{
		Map<String,WxMenu> menuMap = menuXmlFactory.getMenuMap();
		WxMenu menu = menuMap.get("commonMenu");
		return createMenu(menu);
	}
}
